package algorithm;

public class LNode {
	
	public int data;
	public LNode next; // 存储后一个节点的地址，存储格式为"algorithm.LNode@4e25154f"
	
	public LNode(int data) {
		this.data = data;
	}
}

package algorithm;
import algorithm.LNode;

public class Linklist {	
	
	public LNode head;
	public int length;
	
	public Linklist() {
		// 初始化链表，头结点存储链表长度
		this.length = 0;
		this.head = new LNode(this.length); 
	}
	
	public boolean append(int node) {
		LNode newNode = new LNode(node);
		LNode tmp = this.head; // 作为遍历指针
		while (tmp.next != null) {
			tmp = tmp.next;
		}
		tmp.next = newNode;
		this.head.data ++;
		return true;
	}
	
	public boolean insert(int node, int index) {
		LNode newNode = new LNode(node);
		LNode tmp = this.head;
		if (index == 0) {
			throw new RuntimeException("索引值不能为零");
		}
		for (int i = 0; i < index; i++) {
			if (i > this.head.data) {
				throw new RuntimeException("索引值无效");
			} else {
				if (i < index - 1) {
					tmp = tmp.next;
				}
			}
		}
		newNode.next = tmp.next;
		tmp.next = newNode;
		this.head.data ++;
		return true;
	}
	
	public boolean delete(int index) {
		LNode tmp = this.head;
		if (index == 0) {
			throw new RuntimeException("索引值不能为零");
		}
		for (int i = 0; i < index; i++) {
			if (i > this.head.data) {
				throw new RuntimeException("索引值无效");
			} else {
				if (i < index - 1) {
					tmp = tmp.next;
				}
			}
		}
		tmp.next = tmp.next.next;
		this.head.data --;
		return true;
	}
	
	public int get(int index) {
		LNode tmp = this.head;
		if (index == 0) {
			System.out.printf("index=0，当前访问的为头结点，返回的为链表长度：%d", this.head.data);
			return this.head.data;
		}
		for (int i = 0; i < index; i++) {
			if (i > this.head.data) {
				throw new RuntimeException("索引值无效");
			} else {
				tmp = tmp.next;
			}
		}
		return tmp.data;
	}
	
	public boolean show() {
		LNode tmp = this.head;
		// System.out.print(this.head.next);
		// System.out.println();


		while (tmp.next != null) {
			System.out.printf("-%d-", tmp.data);
			tmp = tmp.next;
		}
		System.out.println();
		return true;
	}
	
	public int len() {
		return this.head.data;
	}
	
	// 由于java中的指针与引用型数据是捆绑的，不同于c/c++，暂时没有想到好的方式将链表真正的清空
	public boolean clear() {
		LNode tmp1 = this.head;

		LNode tmp2;
		while (tmp1.next != null) {
			tmp2 = tmp1.next;
			tmp1.next = null; // 此处只是解除了节点之间的关系
			tmp1 = tmp2;
		}
		
		return true;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Linklist Llist = new Linklist();
		Llist.append(8);
		Llist.append(4);
		Llist.insert(2, 3);
		Llist.delete(2);
		// Llist.show();		

		Llist.clear();
		Llist.show();		
	}

}
